using System;
using System.Diagnostics;

namespace ITProf.Applications.pdb2gac.GacUtil
{
    internal static class GacUtilHelper
    {
        private const int timeout = 5000;
        private static string gacutil = "gacutil.exe";

        public static AssemblyInfo? GetGacAssemblyInfo(string assemblyName)
        {
            try
            {
                string gacutilArguments = String.Format("/l {0}", assemblyName);
                ProcessStartInfo startInfo = new ProcessStartInfo(gacutil, gacutilArguments);
                startInfo.RedirectStandardOutput = true;
                startInfo.RedirectStandardError = false;
                startInfo.UseShellExecute = false;
                startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                Process process = new Process();
                process.StartInfo = startInfo;
                process.Start();
                process.WaitForExit(timeout);
                string output = process.StandardOutput.ReadToEnd();
                if (output != null)
                {
                    if (output.IndexOf("Number of items = 1") != -1)
                    {
                        output = output.Replace(Environment.NewLine, "");
                        AssemblyInfo info = new AssemblyInfo();
                        info.Version = GacUtilOutputParser.ParseVersion(output);
                        info.Name = assemblyName;
                        info.PublicKeyToken = GacUtilOutputParser.ParsePublicKeyToken(output);
                        info.ProcessorArchitecture = GacUtilOutputParser.ParseProcessorArchitecture(output);
                        info.Culture = GacUtilOutputParser.ParseCulture(output);
                        return info;
                    }
                    if (output.IndexOf("Number of items = 0") != -1)
                    {
                        return null;
                    }
                }
                throw new ApplicationException(output);
            } catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
            }
            return null;
        }
    }
}